//
//  TSignUpViewController.m
//  LoveShare
//
//  Created by ways on 2017/4/19.
//  Copyright © 2017年 tikeyc. All rights reserved.
//

#import "TSignUpViewController.h"
#import "TSignUpViewModel.h"
#import "TLoginButton.h"

@interface TSignUpViewController ()

@property (nonatomic,strong)TSignUpViewModel *signUpViewModel;
@property (nonatomic,strong)dispatch_source_t timer;

@property (strong, nonatomic) IBOutlet UITextField *mobileTextField;
@property (strong, nonatomic) IBOutlet UITextField *verifiCodeTextField;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
@property (strong, nonatomic) IBOutlet UITextField *confirPasswordTextField;
@property (strong, nonatomic) IBOutlet TLoginButton *registButton;
@property (strong, nonatomic) IBOutlet UIButton *verifiCodeButton;

- (IBAction)registButtonAction:(UIButton *)sender;
- (IBAction)verufuCodeButtonAction:(UIButton *)sender;

@end

@implementation TSignUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = @"注册";

    [self initProperty];
    
    [self initBind];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - init

- (void)initProperty {
    [self initNavigationBarItem];
    
}


- (void)initNavigationBarItem {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
    
    button.frame = CGRectMake(0, 0, 44, 44);
    [button setImage:[UIImage imageNamed:@"common_back_barItem_button"] forState:UIControlStateNormal];
    @weakify(self);
    [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        if (self.timer) {
            dispatch_source_cancel(self.timer);
        }
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}


- (TSignUpViewModel *)signUpViewModel {
    if (!_signUpViewModel) {
        _signUpViewModel = [[TSignUpViewModel alloc] initSignViewModel];
    }
    return _signUpViewModel;
}


- (void)initBind {
    @weakify(self)
    RAC(self.signUpViewModel.signUpModel,mobile) = [[self.mobileTextField rac_textSignal] map:^id _Nullable(NSString * _Nullable value) {
        @strongify(self)
        //判断手机号码
        if ([TKCAppTools valiMobile:value]) {
            self.mobileTextField.textColor = [UIColor blackColor];
        } else{
            self.mobileTextField.textColor = [UIColor redColor];
        }
        return value;
    }];
    
    RAC(self.signUpViewModel.signUpModel,verifiCode) = [[self.verifiCodeTextField rac_textSignal] map:^id _Nullable(NSString * _Nullable value) {
//        @strongify(self)
        return value;
    }];
    
    RAC(self.signUpViewModel.signUpModel,password) = [[self.passwordTextField rac_textSignal] map:^id _Nullable(NSString * _Nullable value) {
        @strongify(self)
        //判断密码长度
        if (value.length >= 6) {
            self.passwordTextField.textColor = [UIColor blackColor];
        } else{
            self.passwordTextField.textColor = [UIColor redColor];
        }
        return value;
    }];
    
    RAC(self.signUpViewModel.signUpModel,confirPassword) = [[self.confirPasswordTextField rac_textSignal] map:^id _Nullable(NSString * _Nullable value) {
        @strongify(self)
        //判断密码长度
        if ([value isEqualToString:self.passwordTextField.text]) {
            self.confirPasswordTextField.textColor = [UIColor blackColor];
        } else{
            self.confirPasswordTextField.textColor = [UIColor redColor];
        }
        return value;
    }];

}

#pragma mark - actions method

- (IBAction)verufuCodeButtonAction:(UIButton *)sender {
    [TAppDelegateManager openBackgroudTask];
    
    self.verifiCodeButton.userInteractionEnabled = NO;
    __block int timeout = 60; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    @weakify(self)
    dispatch_source_set_event_handler(_timer, ^{
        @strongify(self)
        if(timeout <= 0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //定时结束后的UI处理
                self.verifiCodeButton.userInteractionEnabled = YES;
                [self.verifiCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
            });
        }else{
            //            NSLog(@"时间 = %d",timeout);
            NSString *strTime = [NSString stringWithFormat:@"发送验证码(%dS)",timeout];
            //            NSLog(@"strTime = %@",strTime);
            dispatch_async(dispatch_get_main_queue(), ^{
                //定时过程中的UI处理9
                [self.verifiCodeButton setTitle:strTime forState:UIControlStateNormal];
                
            });
            
            timeout--;
        }
    });
    dispatch_resume(_timer);

}

- (IBAction)registButtonAction:(UIButton *)sender {
    [self.view endEditing:YES];
    
    [SVProgressHUD dismissWithDelay:0.5];
    [SVProgressHUD setInfoImage:nil];
    //判断手机号码
    if (![TKCAppTools valiMobile:self.mobileTextField.text]) {
        [SVProgressHUD showErrorWithStatus:@"手机号码格式错误"];
        return;
    }
    
    if (![self.passwordTextField.text isEqualToString:self.confirPasswordTextField.text]) {
        
        [SVProgressHUD showErrorWithStatus:@"密码不一致"];
        [_registButton errorRevertAnimationCompletion:^{
            
        }];
        return;
    }
    
    self.view.userInteractionEnabled = NO;
    @weakify(self)
    [[self.signUpViewModel.requestCommand execute:nil] subscribeNext:^(id responseObject) {
        @strongify(self)
        self.view.userInteractionEnabled = YES;
//        NSLog(@"x:%@",x);
        if ([self.signUpViewModel.signUpModel.msgCode intValue] == 100) {//注册成功
            if (self.userNameBlock) {
                self.userNameBlock(self.mobileTextField.text);
            }
            if (self.timer) {
                dispatch_source_cancel(self.timer);
            }
            [SVProgressHUD showSuccessWithStatus:@"注册成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self dismissViewControllerAnimated:YES completion:^{
                    
                }];
            });
            
        } else {
            [SVProgressHUD showErrorWithStatus:self.signUpViewModel.signUpModel.message];
        }
    }];
}

@end







